import React from 'react';
import {inject, observer} from 'mobx-react';
import { Icon, Tools, Result , TextareaItem , Bubble, Button, Modal} from 'weaver-mobile';
import { withRouter } from 'react-router-dom';
import { RouteLayout } from 'weaver-mobile-page';
import MeetingUtil from '../../util/meetingUtil';
import * as API from '../../api/signInfo';
import { toJS } from 'mobx';
const alert = Modal.alert;
const ButtonGroup = RouteLayout.ButtonGroup;
const getLabel = Tools.getLabel;
const store = ['signInfoStore','viewMeetingStore'];
@inject(...store)
@withRouter
@observer
class SignResult extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
          remark: ''
        };
      }
    componentDidMount() {
      let { signMeeting, setState, signAndGetAddress} = this.props.signInfoStore;
      const searchInfo = this.props.location.search ? this.props.location.search.split('?')[1]:''
      const search = searchInfo.length > 0 ?searchInfo.split('&'):[]
      let params = this.getQuery(search);
      let meetingid = '';
      if(params.meetingid){
        meetingid = params.meetingid.length > 32?params.meetingid.substring(32,):params.meetingid;
      }
      // let meetingid = params.meetingid && params.meetingid.substring(32,);
      setState({meetingid: meetingid})
      API.getScanMillTime().then((res)=>{
        params = {...params,scan_ts:res.millTime}
        if(params.latitude&&params.longitude){
          signMeeting(params);
        }else{
          if((params.getAddress&&params.getAddress=='1') || (res.getSignLocation == 1)){
            signAndGetAddress(params);
          }else if((params.getAddress&&params.getAddress=='0') || (res.getSignLocation == 0)){
            signMeeting(params);
          }else{
            signAndGetAddress(params);
          }
        }
      })
    }

    componentWillUnmount () {
      if(window.em && window.em.closeWindow){
        window.em.checkJsApi('closeWindow') && window.em.closeWindow();
      }
    }

    componentWillReceiveProps(nextProps){
      let { signStatus } = this.props.signInfoStore;
      const prePath = this.props.location.pathname;
      const curPath = nextProps.location.pathname;
      if (curPath == "/signResult") {
        if(signStatus==0||signStatus=='-6'){
          window.em && window.em.checkJsApi('changeTitle') && window.em.changeTitle({ title: getLabel(129698, '签到成功') })
        }else if(signStatus=='-7'||signStatus=='-5'||signStatus=='-1024'||signStatus=='-8'||signStatus=='-1'||signStatus=='-13'){
          window.em && window.em.checkJsApi('changeTitle') && window.em.changeTitle({ title: getLabel(129709, '签到失败') })
        }else if(signStatus=='-11'||signStatus=='-10'){
          window.em && window.em.checkJsApi('changeTitle') && window.em.changeTitle({ title: getLabel(514367, '签退成功') })
        }else if(signStatus=='-12'||signStatus=='-14'){
          window.em && window.em.checkJsApi('changeTitle') && window.em.changeTitle({ title: getLabel(514368, '签退失败') })
        }else if(signStatus.indexOf('-15')>-1){
          window.em && window.em.checkJsApi('changeTitle') && window.em.changeTitle({ title: getLabel(514368, '签退失败') })
        }
      }
    }

    componentWillUpdate(nextProps){
    }

    componentDidUpdate(nextProps){
      const infoRightheight = document.getElementById('meetingInfoRight')&&document.getElementById('meetingInfoRight').offsetHeight
      if(this.refs&&this.refs.meetingInfoLeft){ this.refs['meetingInfoLeft'].style.height=infoRightheight+'px'}
    }

    getQuery = (search)=>{
      let params ={}
      search.map((v,index)=>{
        const tempV = v.split('=')
        params[tempV[0]] = tempV[1]
      });
      return params
    }

    judgeSignStatus = (type) => {
      if (['0','-11', '-10'].indexOf(type) > -1) {
        return true;
      } else {
        return false;
      }
    }

    getExchangeLabel = (params)=>{
      let label = params && params.split('(')[0] ? params.split('(')[0] : params ;
      var res = label;
			if (label && typeof (label) == 'string') {
				var L = label.split('_');
				if (L.length == 2 ) {
					res = L[0] + getLabel(507059,'排') + L[1] + getLabel(507060,'座');
				}
      }
      if ( params && params.split('(')[1] ) res = res + '(' + params.split('(')[1];
			return res;

    }

    render(){
      const receiptHeight = this.getHeight(); 
      let { signStatus , signMsg ,meetingInfo , signTime ,signBackTime, visible, curURL, meetingid, subLoadding, canview } = this.props.signInfoStore;
      let minute = '';
      let s = 0;
      let message = '';
      if(signStatus.indexOf("_")>-1){
          s = signStatus.split("_")[0];
          minute = signStatus.split("_")[1];
          message = signMsg[s].replace('{minute}',minute);
      }else{
        message = signMsg[signStatus];
      }
      let isSignOut = false;
      meetingInfo = toJS(meetingInfo);
      const { ecCallerVisible } = this.props.viewMeetingStore
      let msg = ()=>{
        return (
          <div className={'result-msg'}>
            {/* <div className={'result-msgTitle'}>{signStatus === '0'? getLabel(390567,'您已成功签到以下会议'):getLabel(129709,'签到失败')}</div>
            {<div className={'result-msgInfo'}>{signStatus === '0'?`${getLabel(20035, '签到时间')}：${signTime}`:signMsg[signStatus]}<span className='leave-early'>早退</span></div>}
            {<div>再次扫码可更新签退时间</div>} */}

            <div className={'result-msgTitle'}>{message}</div>
            {this.judgeSignStatus(signStatus) && <div className={'result-msgInfo'} 
               dangerouslySetInnerHTML={{ __html: `${signStatus==='0'?getLabel(20035, '签到时间'): getLabel('20039','签退时间')}：${signStatus==='0'? signTime : signBackTime}` }} 
              >
              {/* {signStatus==='-11' && <span className='leave-early'>{getLabel('20082','早退')}</span>} */}
            </div>}
            {signStatus!=='0'&&this.judgeSignStatus(signStatus) && <div>{getLabel('510283','再次扫码可更新签退时间')}</div>}
          </div>
        )
      };
      
      const signInfoData = signStatus?parseInt(signStatus,10) > 0 ? 
        (<div className={'attendReason'} style={{'height':receiptHeight}}>
          <TextareaItem
              placeholder={getLabel(129711, '请填写参会说明')}
              // autoHeight = {true}
              style={{height:receiptHeight-MeetingUtil.getButtonHeight()}}
              // rows={10}
              onChange = {(value)=>{this.setState({remark:value})}}
            />
            <Button className='savebuttong'  loading={subLoadding} disabled ={subLoadding} type='primary' onClick={() => {this.saveRemark()}}>{getLabel(725, '提交')}</Button>

        </div>)
        :(
        <div className={'signInfo-content'} >
          <div className={'signInfo-content-head'}>
            <Result
                img={<Icon type={this.judgeSignStatus(signStatus)?'sign-in-success':'sign-in-failure'} size={'lg'} color={this.judgeSignStatus(signStatus)?'#6BC15E':'#ED7777'} />}
                message={msg()}
                className={'resultHead'}
              />
          </div>
          <div  className={'meetingInfo'}>
            <div className={`meetingInfo-left-${meetingInfo.meetingStatus}`} ref='meetingInfoLeft'></div>
            {meetingInfo != undefined && JSON.stringify(meetingInfo) != '{}' && <div className={'meetingInfo-right'} id={'meetingInfoRight'}>
              <div className={'meetingInfo-right-head'}>
                <span className={'meetingInfo-name'}>
                  {meetingInfo.name}
                </span>
                {ecCallerVisible && <span className={'meetingInfo-caller'}>
                  {getLabel(2152, '召集人')}：{meetingInfo.caller}
                </span>}
              </div>
              <div className={'meetingInfo-right-detail'}>
                <div style={{display:'flex'}}>
                  <div className={'meetingInfo-label'}>
                    <span>
                      {getLabel(24979, '开始时间')}：
                    </span>
                  </div>
                  <div  className={'meetingInfo-value'}>
                    <span>
                      {meetingInfo.beginDateTime}
                    </span>
                  </div>
                </div>
                <div style={{display:'flex'}}>
                  <div className={'meetingInfo-label'}>
                    <span>
                      {getLabel(743, '结束时间')}：
                    </span>
                  </div>
                  <div  className={'meetingInfo-value'}>
                    <span>
                      {meetingInfo.endDateTime}
                    </span>
                  </div>
                </div>
                <div style={{display:'flex'}}>
                  <div className={'meetingInfo-label'}>
                    <span>
                      {getLabel(2105, '会议地点')}：
                    </span>
                  </div>
                  <div  className={'meetingInfo-value'}>
                    <span>
                      {meetingInfo.address}
                    </span>
                  </div>
                </div>
                {meetingInfo.seat&&<div style={{display:'flex'}}>
                  <div className={'meetingInfo-label'}>
                    <span>
                      {getLabel(15801, '座位号')}：
                    </span>
                  </div>
                  <div  className={'meetingInfo-value'}>
                    <span>
                      {this.getExchangeLabel(meetingInfo.seat)}
                    </span>
                  </div>
                </div>}
              </div>
            </div>}
          </div>
          {canview&&<div className='preview-meetinginfo'>
            <Button type='primary' onClick={() => {this.props.history.push(`/signResult/preview?meetingid=${meetingid}`)}}>{getLabel('503827','查看会议详情') }</Button>
          </div>}
        </div>
      ):'';
  
      return (
        <div>
        <Icon type="loading" style={{zIndex:'9999',position: 'absolute', left: '50%', top: '50%',display: visible}}/>
        {signInfoData}
        <RouteLayout.Frame
          id="viewframe"
          path={'/signResult/preview'}
          iframeProps={{
            src: `/spa/meeting/static4mobile/index.html#/calendar/detail?meetingid=${meetingid}`,
          }}
        />
        </div>
      );  
    }
    getHeight = () => {
      return document.body.clientHeight;
    }
  
    saveRemark = ()=>{
      let { saveRemark, setState, saveRemarkAndGetAddress} = this.props.signInfoStore;
      const searchInfo = this.props.location.search ? this.props.location.search.split('?')[1]:''
      const search = searchInfo.length > 0 ?searchInfo.split('&'):[]
      let params = this.getQuery(search);
      if(this.state.remark === ''){
        alert(getLabel(384434,'您还有必填项未填写'))
      }else{
        API.getScanMillTime().then((res)=>{
          params = {...params,scan_ts:res.millTime,remark:this.state.remark}
          if(params.latitude&&params.longitude){
            saveRemark(params);
          }else{
            if((params.getAddress&&params.getAddress=='1') || (res.getSignLocation == 1)){
              saveRemarkAndGetAddress(params);
            }else if(params.getAddress&&params.getAddress=='0' || (res.getSignLocation == 0)){
              saveRemark(params);
            }else{
              saveRemarkAndGetAddress(params);
            }
            
          }
        })
      }
    }
}

export default SignResult;